<?php

namespace App\Admin\Actions;

use App\Constant\Enum;
use App\Constant\User\UserMode;
use App\Models\User;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;


class BanUserForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $userId = $input['user_id'] ?? 0;
        $action = $input['status'] ?? '';
        $remark = $input['remark'] ?? '';
        $modes = $input['mode'] ?? '';
        $isShowAd = $input['is_show_ad'] ?? '-1';

        if (!in_array($action, [
            Enum::STATUS_ENABLED,
            Enum::STATUS_DISABLED,
            Enum::STATUS_BLOCKED,
        ])) {
            return response()->json([
                'code' => 400,
                'message' => '审核状态无效'
            ]);
        }

        /** @var User $user */
        $user = User::query()->find($userId);
        if (!$user) {
            return response()->json([
                'code' => 400,
                'message' => '用户不存在！'
            ]);
        }
        $mode = 0;
        if (!empty($modes)) {
            foreach ($modes as $m) {
                $mode |= (int)$m;
            }
        }

        try {
            $user->markAs($action, $mode, $remark, $isShowAd);
            return response()->json([
                'code' => 200,
                'message' => '操作成功！'
            ]);
        } catch (\Exception $exception) {
            return response()->json([
                'code' => 400,
                'message' => $exception->getMessage(),
            ]);
        }
    }

    public function form()
    {
        // $this->text('message', '确认信息')->value($this->payload['message'] ?? '')->readOnly();
        /** @var User $user */
        $user = User::query()->findOrFail($this->payload['key']);
        $this->hidden('user_id')->value($this->payload['key']);
        $this->radio('status', '状态')
            ->default(Enum::STATUS_ENABLED)
            ->options([
                Enum::STATUS_ENABLED => '启用',
                Enum::STATUS_BLOCKED => '封禁',
            ])->required()->help('封禁后用户将无法登录');
        $mode = $user->mode;
        $modes = [];
        foreach (UserMode::all() as $flag) {
            if (($mode & $flag) === $flag) {
                $modes[] = $flag;
            }
        }

        $this->checkbox('mode', '行为控制')
            ->default($modes)
            ->options([
                UserMode::DISABLE_WITHDRAW => '禁止提现',
                UserMode::DISABLE_SHARE => '无法分享',
            ]);
        $this->switch('is_show_ad', '启用广告')
            ->default($user->is_show_ad);


        $this->textarea('remark', '备注')->default($user->remark);
    }

    /**
     * 设置表单保存成功后执行的JS
     *
     * @return string|void
     */
    protected function savedScript()
    {
        return <<<JS
        if (data.code != 200) {
            Dcat.error(data.message);
            return false;
        }

        Dcat.success(data.message);
        Dcat.reload();

        return false;
JS;
    }

    /**
     * 设置表单保存失败后执行的JS
     *
     * @return string|void
     */
    protected function errorScript()
    {
        return <<<JS
        var errorData = JSON.parse(response.responseText);
        if (errorData) {
            if (errorData.message) {
                Dcat.error(errorData.message);
            } else {
                Dcat.error("封禁原因必填");
            }
        } else {
            console.log('提交出错', response.responseText);
        }
        // 终止后续逻辑执行（默认逻辑）
        return false;
JS;
    }
}
